# Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import errno
import inspect
import os
import os.path as osp
import shutil
import sys
import traceback
from dataclasses import asdict
from getpass import getuser
from importlib.util import module_from_spec, spec_from_file_location
from tempfile import gettempdir
from typing import Any, Callable, Dict, List, Optional, Union

import requests
from fastapi import HTTPException
from pydantic import BaseModel

from lightning.app.utilities import frontend
from lightning.app.utilities.app_helpers import Logger, is_overridden
from lightning.app.utilities.cloud import _get_project
from lightning.app.utilities.network import LightningClient
from lightning.app.utilities.state import AppState

logger = Logger(__name__)

class ClientCommand:
    description: str = ""
    requirements: List[str] = []

    def __init__(self, method: Callable):
        self.method = method
        if not self.description:
            self.description = self.method.__doc__ or ""
        flow = getattr(self.method, "__self__", None)
        self.owner = flow.name if flow else None
        self.models: Optional[Dict[str, BaseModel]] = None
        self.app_url = None
        self._state = None

    @property
    def state(self):
        if self._state is None:
            self._state = AppState(host=self.app_url)
            self._state._request_state()
        return self._state

